package com.cresch.ical.downloader;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.cresch.ical.downloader.ical.Calendar;
import com.cresch.ical.downloader.ical.VEvent;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;


public class CalendarView extends Activity implements Runnable{
	
	private String rawCalendarString;
	private List<String> event_list;
	private ProgressDialog progressDialog;
	private final int EVENTS_PER_DISPLAY = 5;
	private Calendar calendar;
	private Button buttonNext;
	private Button buttonPrev;
	private Button buttonClose;
	private ListView eventsView;
	private ArrayList<VEvent> currentEventList;

	private final Handler messageHandler = new Handler() {

        @Override
        public void handleMessage(final Message msg) {
        	if (progressDialog != null) {        		
        		progressDialog.dismiss();
        	}

			showNextCalendarEntrys();
        }
    }; 

	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
        setContentView(R.layout.calendar_view);
    	
    	event_list = new ArrayList<String>();
    	currentEventList = new ArrayList<VEvent>();
    	calendar = new Calendar();
		rawCalendarString = null;
    	
        progressDialog = new ProgressDialog(this);
    	progressDialog.setIndeterminate(true);
    	progressDialog.setCancelable(false);
		progressDialog = ProgressDialog.show(this, "Step 2 . . .", "building Timetable");
		final Thread parserThread = new Thread(this);
		parserThread.start();

        
        buttonNext = (Button) findViewById(R.id.NextDay);
        buttonNext.setOnClickListener(new OnClickListener(){
        	public void onClick(final View v) {
        		showNextCalendarEntrys();
        	}
        });
        
        buttonPrev = (Button) findViewById(R.id.PrevDay);
        buttonPrev.setOnClickListener(new OnClickListener(){
        	public void onClick(final View v) {
        		showPreviousCalendarEntrys();
        	}
        });
    	        
        eventsView = (ListView) findViewById(R.id.list);
        eventsView.setOnItemClickListener(new OnItemClickListener(){
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				showEventDetails(arg2);
				
			}        	
        });
        
        buttonClose = (Button) findViewById(R.id.Close);
        buttonClose.setOnClickListener(new OnClickListener(){
        	public void onClick(final View v) {
        		finish();
        	}
        });
    }
    
    private void showEventDetails(int index) {
    	Bundle data = new Bundle();
		
    	String dateTime;
    	dateTime = formatEventDate(currentEventList.get(index).getStart(), currentEventList.get(index).getEnd());
		data.putString(EventDetail.DATETIME, dateTime);
		data.putString(EventDetail.DESCRIPTION, currentEventList.get(index).getDescription());
		data.putString(EventDetail.LOCATION, currentEventList.get(index).getLocation());
		
		Intent eventDetail = new Intent(this, EventDetail.class);
		eventDetail.putExtras(data);		      
		this.startActivityForResult(eventDetail, 0);
    }
    
    private void showNextCalendarEntrys() {
    	    
    	event_list.clear();
    	currentEventList.clear();
    	for (Integer i = 0; i < EVENTS_PER_DISPLAY; i++) {
    		String event_info;
    		event_info = formatEventDate(calendar.getCurrentEvent().getStart(), calendar.getCurrentEvent().getEnd());
    		event_info = event_info.concat("\n");
    		event_info = event_info.concat(calendar.getCurrentEvent().getSummary());
    		
    		event_list.add(event_info);
    		currentEventList.add(calendar.getCurrentEvent());
    		
    		calendar.setNextEvent();
		}
    	
    	ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.calendar_listview, R.id.entry_summary, event_list);
    	//this.setListAdapter(adapter);
    	this.eventsView.setAdapter(adapter);
    	
    }
    
    private void showPreviousCalendarEntrys() {    	
    	
    	// step back actual displayed events
    	for (Integer i = 0; i < EVENTS_PER_DISPLAY; i++) {
    		calendar.setPrevEvent();
    	}
    	
    	// show previous events
    	event_list.clear();
    	currentEventList.clear();
    	for (Integer i = 0; i < EVENTS_PER_DISPLAY; i++) {
    		calendar.setPrevEvent();
    		
    		String event_info;
    		event_info = formatEventDate(calendar.getCurrentEvent().getStart(), calendar.getCurrentEvent().getEnd());
    		event_info = event_info.concat("\n");
    		event_info = event_info.concat(calendar.getCurrentEvent().getSummary());
    		
    		event_list.add(event_info);
    		currentEventList.add(calendar.getCurrentEvent());
		}
    	
    	ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.calendar_listview, R.id.entry_summary, event_list);
    	this.eventsView.setAdapter(adapter);
    }
	
	private String formatEventDate(Date start, Date end) {
		String dateTime;
		
		DateFormat df = new SimpleDateFormat("dd.MM yyyy HH:mm");
		dateTime = df.format(start);
		
		df = new SimpleDateFormat("HH:mm");
		dateTime = dateTime.concat(" - "+ df.format(end));
		
		return dateTime;
	}

		@Override
		public void run() {
			if (rawCalendarString == null) {
				Bundle data = getIntent().getExtras();
				rawCalendarString = data.getString(Main.CALENDAR_RAW_DATA);
			}
			if (calendar != null) {
				calendar.Build(rawCalendarString);
				messageHandler.sendEmptyMessage(0);
			}
		} 
}


